package ru.romannep.and.chopperbattle;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class ViewThread extends Thread {
	private GameView gameView;
	private SurfaceHolder surfaceHolder;
	private boolean isRunning;

	public ViewThread(GameView gameView) {
		this.gameView = gameView;
		surfaceHolder = gameView.getHolder();
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}

	public boolean isRunning() {
		return isRunning;
	}

	@Override
	public void run() {
		Canvas canvas;
		long calcTill = System.currentTimeMillis();
		long now = calcTill;
		Log.v(ChopperBattleMain.TAG, "In ViewThread: starting");
		//gameView.initObjects();
		while (isRunning) {
			now = System.currentTimeMillis();
			
			if (now > calcTill) {// do game cycle
				gameView.testGameCycle();
				
				calcTill += ChopperBattleMain.MS_PER_CYCLE; 
			} // do game cycle

			now = System.currentTimeMillis();
			
			if (now < calcTill) {// do draw
				canvas = null;
				try {
					canvas = surfaceHolder.lockCanvas(null);
					synchronized (surfaceHolder) {
						gameView.doDraw(canvas);
					}
				} finally {
					if (canvas != null) {
						surfaceHolder.unlockCanvasAndPost(canvas);
					}
				}
				
			} // do draw
			

		}
		Log.v(ChopperBattleMain.TAG, " ViewThread stopped");

	}

}
